# This file is part of sddpy.

# sddpy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# sddpy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with sddpy.  If not, see <http://www.gnu.org/licenses/>.

import _sddpy
class Error(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class LookupError(Error):
    pass

class Dict(object):
    pass

class Dicts(object):
    def __init__(self, path):
        self.path = path
        self._dicts = _sddpy.Dicts(path)
        self.ids = {}
        for i in xrange(self._dicts.ndicts()):
            self.ids[self._dicts.dict_name(i)]=i

    def __getitem__(self, key):
        d=Dict()
        d.lookup=lambda word: self.lookup(key, word.encode('utf-8'))
        d.name=key
        return d
    
    def __iter__(self):
        self.i=0
        return self

    def next(self):
        if self.i<self._dicts.ndicts():
            name=self._dicts.dict_name(self.i)
            self.i+=1
            return self[name]
        else:
            raise StopIteration

    def lookup(self, dict, word):
        try:
            return self._dicts.lookup(self.ids[dict], word)
        except _sddpy.error:
            raise LookupError('Word not found.')


if __name__ == '__main__':
    d=Dicts('/home/davidov/.stardict/dic')
    #print d.ids
    #print d['Mueller7GPL'].lookup('word')
    #print d.lookup('Mueller7GPL', 'wordd')
    for j in xrange(2):
        for i in d:
            print i.name
            try:
                print i.lookup(u'word')
            except LookupError:
                print "Not found"
